package com.proton.carepatchtemp.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.activity.ReportDetailActivity;
import com.proton.carepatchtemp.adapterholder.ReportHolder;
import com.proton.carepatchtemp.base.MyDialogFragment;
import com.proton.carepatchtemp.constant.Config;
import com.proton.carepatchtemp.constant.DialogCodes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.table.Report;
import com.proton.carepatchtemp.fragment.ShareReportFragment;
import com.proton.carepatchtemp.utils.FormatUtils;
import com.proton.carepatchtemp.utils.NetUtils;
import com.proton.carepatchtemp.utils.NumUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.net.ReportCenter;
import com.sdsmdg.tastytoast.TastyToast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by MoonlightSW on 2016/11/17.
 */

public class ReportListAdapter extends RecyclerView.Adapter<ReportHolder> implements MyDialogFragment.OnDialogListener {

    public List<Report> mReports;
    //  是否批量删除
    public boolean isBulkDeletion = false;
    //  批量删除列表
    //  id列表
    public List<String> mDeleteList = new ArrayList<>();
    //  Report对象列表
    public List<Report> mDelReportList = new ArrayList<>();
    //  是否为需要在删除完后显示收藏的报告 0 全部 1 收藏
    public int isCollect = 0;
    private int position;
    private Context mContext = null;
    private FragmentManager mFragmentManager = null;
    private LayoutInflater mInflater;

    public ReportListAdapter(Context context, ArrayList<Report> rpts, FragmentManager fragmentManager) {
        mReports = rpts;
        if (null != context) {
            mContext = context;
            mInflater = LayoutInflater.from(mContext);
        } else return;

        this.mFragmentManager = fragmentManager;
    }

    @Override
    public ReportHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_report, parent, false);
        ReportHolder holder = new ReportHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ReportHolder holder, int position) {
        if (null == mReports.get(position)) {
            return;
        }

        if (1 == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
            holder.mTv_report_unit.setText("℃");
        } else {
            holder.mTv_report_unit.setText("℉");
        }

        Report temp = mReports.get(position);
        Report.DataBean tempDataBean = temp.getData();

        //  是否批量删除
        if (isBulkDeletion) {
            holder.mSwipeMenuLayout.setSwipeEnable(false);
            holder.mcb_report_select.setVisibility(View.VISIBLE);
            holder.mcb_report_select.setChecked(temp.isChecked());
            holder.mcb_report_select.setOnClickListener(v -> {
                if (mDelReportList.contains(temp)) {
                    temp.setChecked(false);
                    holder.mcb_report_select.setChecked(false);
                    mDelReportList.remove(temp);
                    mDeleteList.remove(temp.getId() + "");
                } else {
                    temp.setChecked(true);
                    holder.mcb_report_select.setChecked(true);
                    mDelReportList.add(temp);
                    mDeleteList.add(temp.getId() + "");
                }
                LogUtils.e(mDeleteList);
                LogUtils.e(mDelReportList);
                LogUtils.e("mDeleteList = " + mDeleteList.toString().replace("[", "").replace("]", ""));
            });
        } else {
            holder.mSwipeMenuLayout.setSwipeEnable(true);
            holder.mcb_report_select.setVisibility(View.GONE);
        }

        holder.mTv_report_time.setText(FormatUtils.getTimeElapse(temp.getStarttime()));

        holder.mSdv_profile_avatar.setImageURI(temp.getProfileavatar());
        holder.mTv_report_prf_name.setText(temp.getProfilename());
        holder.mTv_test_sum_time.setText(FormatUtils.formatTime(temp.getEndtime() - temp.getStarttime()));

        //  删除按钮
        holder.mIv_delete.setOnClickListener(view -> {
            if (NetUtils.noNet()) {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                return;
            }
            this.position = position;
            MyDialogFragment myDialogFragment = MyDialogFragment.newInstance(DialogCodes.RPT_DELETE, null);
            myDialogFragment.setOnDialogListener(ReportListAdapter.this);
            myDialogFragment.setTitle(mContext.getString(R.string.string_delete_confirm));
            myDialogFragment.setMsg(mContext.getString(R.string.string_delete_report_warm));
            myDialogFragment.show(mFragmentManager, "delete_report");
            holder.mSwipeMenuLayout.quickClose();
        });

        View.OnClickListener onClickListener = (view) -> {
            if (NetUtils.noNet()) {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                return;
            }
            Intent goDetial = new Intent(mContext, ReportDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Extras.REPORT, temp);
            goDetial.putExtras(bundle);
//            goDetial.putExtra(Extras.REPORTID,temp.getId());
            mContext.startActivity(goDetial);
        };
        holder.mFrl_report_item.setOnClickListener(onClickListener);

        //  popupWindow菜单
        if (temp.isCollect()) {
            holder.mIv_collect.setVisibility(View.VISIBLE);
        } else {
            holder.mIv_collect.setVisibility(View.GONE);
        }
        holder.mIv_more_choices.setOnClickListener(view -> {
            if (NetUtils.noNet()) {
                TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                return;
            }
            View contentView = mInflater.inflate(
                    R.layout.report_popupwindow, null);
            final PopupWindow popupWindow = new PopupWindow(contentView,
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

            TextView mTv_report_collect = contentView.findViewById(R.id.tv_report_collect);
            TextView mTv_report_share = contentView.findViewById(R.id.tv_report_share);

            if (temp.isCollect()) {
                mTv_report_collect.setText(mContext.getString(R.string.string_has_marked));
                mTv_report_collect.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, R.mipmap.collect_yellow_full), null, null, null);
            } else {
                mTv_report_collect.setText(R.string.string_marked);
                mTv_report_collect.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, R.mipmap.collect_yellow_null), null, null, null);
            }

            mTv_report_collect.setOnClickListener(view1 -> {
                if (NetUtils.noNet()) {
                    TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                    return;
                }
                if (temp.isCollect()) {
                    ReportCenter.cancelCollect(temp.getId());
                    holder.mIv_collect.setVisibility(View.GONE);
                    mTv_report_collect.setText(R.string.string_marked);
                    mTv_report_collect.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, R.mipmap.collect_yellow_null), null, null, null);
                    temp.setCollect(false);
                    if (1 == isCollect) {
                        popupWindow.dismiss();
                        mReports.remove(position);
                        notifyDataSetChanged();
                    }
                } else {
                    ReportCenter.collect(temp.getId());
                    holder.mIv_collect.setVisibility(View.VISIBLE);
                    mTv_report_collect.setText(mContext.getString(R.string.string_has_marked));
                    mTv_report_collect.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(mContext, R.mipmap.collect_yellow_full), null, null, null);
                    temp.setCollect(true);
                }
            });

            mTv_report_share.setOnClickListener(view1 -> {
                if (NetUtils.noNet()) {
                    TastyUtils.makeTextShort(R.string.have_no_netconnect, TastyToast.CONFUSING);
                    return;
                }
                ShareReportFragment shareReportFragment = new ShareReportFragment();
                shareReportFragment.setReport(mReports.get(position));
                shareReportFragment.show(((AppCompatActivity) mContext).getSupportFragmentManager(), String.valueOf(mReports.get(position).getId()));
            });

            popupWindow.setTouchable(true);
            // 使其聚焦
            popupWindow.setFocusable(true);
            // 设置允许在外点击消失
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
            //刷新状态
            popupWindow.update();
            popupWindow.setTouchInterceptor((v, event) -> {
                return false;
            });
            popupWindow.showAsDropDown(view);
        });

        if (null == tempDataBean) {
            return;
        } else {
            //在显示范围内再显示
            if (NumUtils.withinTempRange(Float.parseFloat(tempDataBean.getTemp_max()))) {
                if (1 == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
                    holder.mTv_highest_temp_rpt.setText(tempDataBean.getTemp_max());
                } else {
                    holder.mTv_highest_temp_rpt.setText(FormatUtils.c2F(Float.parseFloat(tempDataBean.getTemp_max())) + "");
                }

                if (25F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) < 35.9F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_not_noraml_temp);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_unusual_bg));
                } else if (35.9F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) < 37.2F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_normal);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_normal_bg));
                } else if (37.2F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) < 38.0F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_low_fever);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_low_fever));
                } else if (38.0F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) < 39F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_middle_fever);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_middle_fever));
                } else if (39F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) < 42F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_high_fever);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_high_fever));
                } else if (42F <= Float.parseFloat(tempDataBean.getTemp_max()) && Float.parseFloat(tempDataBean.getTemp_max()) <= 45F) {
                    holder.mTv_high_or_low_rpt.setText(R.string.string_not_noraml_temp);
                    holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_unusual_bg));
                }
            } else {
                if (25 > Float.parseFloat(tempDataBean.getTemp_max())) {
                    if (1 == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
                        holder.mTv_highest_temp_rpt.setText("< 25.00");
                    } else {
                        holder.mTv_highest_temp_rpt.setText("< 77.00");
                    }
                } else {
                    if (1 == SpUtils.getInt(Extras.TEMP_UNIT, Config.TEMP_UNIT_DEFAULT)) {
                        holder.mTv_highest_temp_rpt.setText("< 45.00");
                    } else {
                        holder.mTv_highest_temp_rpt.setText("< 113.00");
                    }
                }

                holder.mTv_high_or_low_rpt.setText(R.string.string_out_of_range_n);
                holder.mTv_high_or_low_rpt.setBackground(ContextCompat.getDrawable(mContext, R.drawable.temp_unusual_bg));
            }
        }
    }

    @Override
    public int getItemCount() {
        return null == mReports ? 0 : mReports.size();
    }

    @Override
    public void onDialogClick(int requestCode, int result) {
        switch (requestCode) {
            case DialogCodes.RPT_DELETE:
                ReportCenter.deleteSome(String.valueOf(mReports.get(position).getId()));
                mReports.remove(position);
                if (mReports.size() <= 0) {
                    ReportCenter.getNewList("0", 1, Extras.RPT_TYPE_TEMP, 0, isCollect, true);
                }
                notifyDataSetChanged();
                break;
        }
    }

}
